package com.tanhua.dubbo.server.api;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.PageUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.dubbo.config.annotation.Service;
import com.tanhua.dubbo.server.enums.CommentType;
import com.tanhua.dubbo.server.enums.IdType;
import com.tanhua.dubbo.server.pojo.*;
import com.tanhua.dubbo.server.service.IdService;
import com.tanhua.dubbo.server.service.TimeLineService;
import com.tanhua.dubbo.server.vo.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.ArrayList;
import java.util.List;


@Service(version = "1.0.0")
@Slf4j
public class QuanZiApiImpl implements QuanZiApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private IdService idService;

    @Autowired
    private TimeLineService timeLineService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Autowired
    private VideoApi videoApi;

    //评论数据存储在Redis中key的前缀
    private static final String COMMENT_REDIS_KEY_PREFIX = "QUANZI_COMMENT_";

    //用户是否点赞的前缀
    private static final String COMMENT_USER_LIEK_REDIS_KEY_PREFIX = "USER_LIKE_";

    //用户是否喜欢的前缀
    private static final String COMMENT_USER_LOVE_REDIS_KEY_PREFIX = "USER_LOVE_";


    private String getCommentRedisKeyPrefix(String publishId) {
        return COMMENT_REDIS_KEY_PREFIX + publishId;
    }

    private String getCommentUserLikeRedisKeyPrefix(Long userId) {
        return COMMENT_USER_LIEK_REDIS_KEY_PREFIX + userId;
    }

    private String getCommentUserLoveRedisKeyPrefix(Long userId) {
        return COMMENT_USER_LOVE_REDIS_KEY_PREFIX + userId;
    }

    private Boolean saveComment(Long userId, String publishId, CommentType commentType, String content) {
        try {
            //将信息存储在comment对象中
            Comment comment = new Comment();
            comment.setId(ObjectId.get());
            comment.setUserId(userId);
            comment.setPublishId(new ObjectId(publishId));
            comment.setCommentType(commentType.getType());
            comment.setContent(content);
            comment.setCreated(System.currentTimeMillis());

            //获取发布动态的用户的id
            Publish publish = this.queryPublishById(publishId);
            if(ObjectUtil.isNotEmpty(publish)){
                comment.setPublishUserId(publish.getUserId());
            }else {
                Comment comment1 =  queryCommentById(publishId);
                if(ObjectUtil.isNotEmpty(comment1)){
                    comment.setPublishUserId(comment1.getUserId());
                }else{
                    //小视频
                    Video video = videoApi.queryVideoById(publishId);
                    if(ObjectUtil.isNotEmpty(video)){
                        comment.setPublishUserId(video.getUserId());
                    }else {
                        return false;
                    }

                }
            }
            //存入mogondb中
            this.mongoTemplate.save(comment);

            return true;
        } catch (Exception e) {
            log.error("保存Comment出错  userId = " + userId + ", publishId = " + publishId + ", commentType = " + commentType, e);
        }

        return false;
    }

    private Comment queryCommentById(String publishId) {
        return mongoTemplate.findById(new ObjectId(publishId),Comment.class);
    }

    //删除评论数据
    private Boolean removeComment(Long userId, String publishId, CommentType commentType) {
        Query query = Query.query(Criteria.where("userId").is(userId)
                .and("publishId").is(new ObjectId(publishId))
                .and("commentType").is(commentType.getType())
        );
        return this.mongoTemplate.remove(query, Comment.class).getDeletedCount() > 0;
    }

    //查询数量
    private Long queryCommentCount(String publishId, CommentType commentType) {
        Query query = Query.query(Criteria.where("publishId").is(new ObjectId(publishId))
                .and("commentType").is(commentType.getType())
        );
        return this.mongoTemplate.count(query, Comment.class);
    }

    @Override
    public PageInfo<Publish> queryPublishList(Long userId, Integer page, Integer pageSize) {

        PageInfo<Publish> pageInfo = new PageInfo<>();
        pageInfo.setPageNum(page);
        pageInfo.setPageSize(pageSize);

        Pageable pageable = PageRequest.of(page - 1, pageSize, Sort.by(Sort.Order.desc("date")));

        List<TimeLine> timeLineList = mongoTemplate.find(new Query().with(pageable), TimeLine.class, "quanzi_time_line_" + userId);

        if(CollUtil.isEmpty(timeLineList)){
            //没有查询到数据
            return pageInfo;
        }

        //获取时间线表所有的id
        List<Object> ids = CollUtil.getFieldValues(timeLineList, "publishId");

        //根据id去查询动态表
        Query publishQuery = Query.query(Criteria.where("id").in(ids)).with(Sort.by(Sort.Order.desc("created")));
        List<Publish> publishList = mongoTemplate.find(publishQuery, Publish.class);

        pageInfo.setRecords(publishList);

        return pageInfo;
    }

    @Override
    public String savePublish(Publish publish) {
        //校验publish对象
        if(!ObjectUtil.isAllNotEmpty(publish.getText(),publish.getUserId())){
            //发布动态失败
            return null;
        }

        //设置主键id
        publish.setId(ObjectId.get());

        try {

            //设置自增长的pid
            publish.setPid(idService.createId(IdType.PUBLISH));
            publish.setCreated(System.currentTimeMillis());

            //写入到publish表中
            mongoTemplate.save(publish);

            //写入相册表
            Album album = new Album();
            album.setId(ObjectId.get());
            album.setCreated(System.currentTimeMillis());
            album.setPublishId(publish.getId());
            mongoTemplate.save(album, "quanzi_album_" + publish.getUserId());

            //写入好友的时间线表（异步写入）
            timeLineService.saveTimeLine(publish.getUserId(), publish.getId());

        }catch (Exception e){
            log.error("发布动态失败  publish = "+ publish , e);
        }

        return publish.getId().toHexString();
    }

    @Override
    public PageInfo<Publish> queryRecommendPublishList(Long userId, Integer page, Integer pageSize) {

        PageInfo<Publish> pageInfo = new PageInfo<>();
        pageInfo.setPageNum(page);
        pageInfo.setPageSize(pageSize);

        //在redis中查询推荐数据
        String data = redisTemplate.opsForValue().get("QUANZI_PUBLISH_RECOMMEND_" + userId);
        if(StrUtil.isEmpty(data)){
            return pageInfo;
        }

        List<String> pids = StrUtil.split(data, ',');

        //分页处理
        int[] startEnd = PageUtil.transToStartEnd(page - 1, pageSize);
        int startIndex = startEnd[0]; //开始
        int endIndex = Math.min(startEnd[1], pids.size()); //结束

        List<Long> pidList = new ArrayList<>();
        for (int i = startIndex; i < endIndex; i++) {
            pidList.add(Long.valueOf(pids.get(i)));
        }

        if(CollUtil.isEmpty(pidList)){
            return pageInfo;
        }

        //根据pid查询publish
        Query query = Query.query(Criteria.where("pid").in(pidList)).with(Sort.by(Sort.Order.desc("created")));
        List<Publish> publishList = mongoTemplate.find(query, Publish.class);
        if (CollUtil.isEmpty(publishList)){
            return pageInfo;
        }

        pageInfo.setRecords(publishList);

        return pageInfo;


    }

    @Override
    public Publish queryPublishById(String id) {
        return mongoTemplate.findById(new ObjectId(id),Publish.class);
    }

    @Override
    public Boolean likeComment(Long userId, String publishId) {
        //先判断是否已经点赞
        if(queryUserIsLike(userId, publishId)){
            return false;
        }

        //保存comment数据
        Boolean result =  saveComment(userId,publishId, CommentType.LIKE,null);
        if(!result){
            return false;
        }

        //修改redis中的点赞数
        String redisKey = getCommentRedisKeyPrefix(publishId);
        String hashKey = CommentType.LIKE.toString();
        redisTemplate.opsForHash().increment(redisKey,hashKey,1);

        //修改成已点赞
        String userHashKey = getCommentUserLikeRedisKeyPrefix(userId);
        redisTemplate.opsForHash().put(redisKey,userHashKey,"1");

        return true;
    }

    @Override
    public Boolean disLikeComment(Long userId, String publishId) {
        //先判断是否点赞
        if(!queryUserIsLike(userId,publishId)){
            return false;
        }

        //删除评论数据
        Boolean result = this.removeComment(userId, publishId, CommentType.LIKE);
        if (!result) {
            return false;
        }

        //修改redis中的点赞数
        String redisKey = getCommentRedisKeyPrefix(publishId);
        String hashKey = CommentType.LIKE.toString();
        redisTemplate.opsForHash().increment(redisKey,hashKey,-1);

        //取消点赞
        String userHashKey = getCommentUserLikeRedisKeyPrefix(userId);
        redisTemplate.opsForHash().delete(redisKey,userHashKey);

        return true;
    }

    @Override
    public Long queryLikeCount(String publishId) {
        //先从redis中查询
        String redisKey = this.getCommentRedisKeyPrefix(publishId);
        String hashKey = CommentType.LIKE.toString();
        Object data = redisTemplate.opsForHash().get(redisKey, hashKey);
        if(ObjectUtil.isNotEmpty(data)){
            return Convert.toLong(data);
        }

        //redis中没查询到 才去查询mongodb
        Long count = queryCommentCount(publishId, CommentType.LIKE);

        //存入到redis中
        redisTemplate.opsForHash().put(redisKey,hashKey,count+"");

        return count;
    }

    @Override
    public Boolean queryUserIsLike(Long userId, String publishId) {
        //先查询redis中是否有是否喜欢的信息
        String redisKey = this.getCommentRedisKeyPrefix(publishId);
        String userHashKey = this.getCommentUserLikeRedisKeyPrefix(userId);
        Object data = this.redisTemplate.opsForHash().get(redisKey, userHashKey);
        if (ObjectUtil.isNotEmpty(data)) {
            return StrUtil.equals(Convert.toStr(data), "1");
        }

        //redis没有则要去mongodb中查询
        Query query = Query.query(Criteria.where("publishId").is(new ObjectId(publishId))
                .and("userId").is(userId)
                .and("commentType").is(CommentType.LIKE));

        long count = mongoTemplate.count(query, Comment.class);
        if(count == 0 ){
            return false;
        }

        //存入到redis中
        redisTemplate.opsForHash().put(redisKey,userHashKey,"1");

        return true;

    }

    @Override
    public Boolean loveComment(Long userId, String publishId) {
        //先判断是否已经喜欢
        if(queryUserIsLove(userId, publishId)){
            return false;
        }

        //保存comment数据
        Boolean result =  saveComment(userId,publishId, CommentType.LOVE,null);
        if(!result){
            return false;
        }

        //修改redis中的喜欢数
        String redisKey = getCommentRedisKeyPrefix(publishId);
        String hashKey = CommentType.LOVE.toString();
        redisTemplate.opsForHash().increment(redisKey,hashKey,1);

        //修改成已点赞
        String userHashKey = getCommentUserLoveRedisKeyPrefix(userId);
        redisTemplate.opsForHash().put(redisKey,userHashKey,"1");

        return true;
    }

    @Override
    public Boolean disLoveComment(Long userId, String publishId) {
        //先判断是否喜欢
        if(!queryUserIsLove(userId,publishId)){
            return false;
        }

        //删除评论数据
        Boolean result = this.removeComment(userId, publishId, CommentType.LOVE);
        if (!result) {
            return false;
        }

        //修改redis中的喜欢数
        String redisKey = getCommentRedisKeyPrefix(publishId);
        String hashKey = CommentType.LOVE.toString();
        redisTemplate.opsForHash().increment(redisKey,hashKey,-1);

        //取消喜欢
        String userHashKey = getCommentUserLoveRedisKeyPrefix(userId);
        redisTemplate.opsForHash().delete(redisKey,userHashKey);

        return true;
    }

    @Override
    public Long queryLoveCount(String publishId) {
        //先从redis中查询
        String redisKey = this.getCommentRedisKeyPrefix(publishId);
        String hashKey = CommentType.LOVE.toString();
        Object data = redisTemplate.opsForHash().get(redisKey, hashKey);
        if(ObjectUtil.isNotEmpty(data)){
            return Convert.toLong(data);
        }

        //redis中没查询到 才去查询mongodb
        Long count = queryCommentCount(publishId, CommentType.LOVE);

        //存入到redis中
        redisTemplate.opsForHash().put(redisKey,hashKey,count+"");

        return count;
    }

    @Override
    public Boolean queryUserIsLove(Long userId, String publishId) {
        //先查询redis中是否有是否喜欢的信息
        String redisKey = this.getCommentRedisKeyPrefix(publishId);
        String userHashKey = this.getCommentUserLoveRedisKeyPrefix(userId);
        Object data = this.redisTemplate.opsForHash().get(redisKey, userHashKey);
        if (ObjectUtil.isNotEmpty(data)) {
            return StrUtil.equals(Convert.toStr(data), "1");
        }

        //redis没有则要去mongodb中查询
        Query query = Query.query(Criteria.where("publishId").is(new ObjectId(publishId))
                .and("userId").is(userId)
                .and("commentType").is(CommentType.LIKE));

        long count = mongoTemplate.count(query, Comment.class);
        if(count == 0 ){
            return false;
        }

        //存入到redis中
        redisTemplate.opsForHash().put(redisKey,userHashKey,"1");

        return true;

    }

    @Override
    public PageInfo<Comment> queryCommenList(String publishId, Integer page, Integer pageSize) {
        PageRequest pageRequest = PageRequest.of(page - 1, pageSize, Sort.by(Sort.Order.asc("created")));
        Query query = new Query(Criteria.where("publishId").is(new ObjectId(publishId)).and("commentType").is(CommentType.COMMENT.getType()))
                .with(pageRequest);

        //查询评论列表
        List<Comment> commentList = mongoTemplate.find(query, Comment.class);

        PageInfo<Comment> pageInfo = new PageInfo<>();
        pageInfo.setPageSize(pageSize);
        pageInfo.setPageNum(page);
        pageInfo.setRecords(commentList);

        return pageInfo;
    }

    @Override
    public Boolean saveComments(Long userId, String publishId, String content) {
        return this.saveComment(userId,publishId,CommentType.COMMENT,content);
    }

    @Override
    public Long queryCommentsCount(String publishId) {
        return queryCommentCount(publishId,CommentType.COMMENT);
    }

    @Override
    public PageInfo<Comment> queryLikeCommentListByUser(Long userId, Integer page, Integer pageSize) {
        return queryCommentsByUser(userId,CommentType.LIKE,page,pageSize);
    }

    @Override
    public PageInfo<Comment> queryLoveCommentListByUser(Long userId, Integer page, Integer pageSize) {
        return queryCommentsByUser(userId,CommentType.LOVE,page,pageSize);

    }

    @Override
    public PageInfo<Comment> queryCommentListByUser(Long userId, Integer page, Integer pageSize) {
        return queryCommentsByUser(userId,CommentType.COMMENT,page,pageSize);

    }

    @Override
    public PageInfo<Publish> queryAlbumList(Long userId, Integer page, Integer pageSize) {
        PageInfo<Publish> pageInfo = new PageInfo<>();
        pageInfo.setPageNum(page);
        pageInfo.setPageSize(pageSize);

        PageRequest pageRequest = PageRequest.of(page - 1 , pageSize,
                Sort.by(Sort.Order.desc("created")));
        Query query = new Query().with(pageRequest);

        //查询相册表
        List<Album> albumList = mongoTemplate.find(query, Album.class, "quanzi_album_" + userId);

        if(CollUtil.isEmpty(albumList)){
            return pageInfo;
        }

        //通过相册集合获取publishId的集合
        List<Object> publishIds = CollUtil.getFieldValues(albumList, "publishId");
        Query publishQuery = Query.query(Criteria.where("id").in(publishIds)).with(Sort.by(Sort.Order.desc("created")));

        List<Publish> publishList = mongoTemplate.find(publishQuery, Publish.class);

        pageInfo.setRecords(publishList);

        return pageInfo;
    }

    private PageInfo<Comment> queryCommentsByUser(Long userId, CommentType commentType, Integer page, Integer pageSize) {
        PageRequest pageRequest = PageRequest.of(page - 1, pageSize,
                Sort.by(Sort.Order.desc("created")));

        Query query = new Query(Criteria
                .where("publishUserId").is(userId)
                .and("commentType").is(commentType.getType())).with(pageRequest);

        List<Comment> commentList = this.mongoTemplate.find(query, Comment.class);

        PageInfo<Comment> pageInfo = new PageInfo<>();
        pageInfo.setPageNum(page);
        pageInfo.setPageSize(pageSize);
        pageInfo.setRecords(commentList);
        return pageInfo;
    }

}
